package com.app.island.cash.requestwork

import com.app.island.cash.BuildConfig
import com.app.island.cash.params.AppParams
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Author: xiaoteng
 * Date: 2016/4/5 10:30
 * Description: 网络请求client
 */
class NetImageClient private constructor() {
    // retrofit实例
    private val retrofit: Retrofit

    /**
     * 创建单例对象
     */
    private object RDClientInstance {
        var instance = NetImageClient()
    }

    companion object {
        // 网络请求超时时间值(s)
        private const val DEFAULT_TIMEOUT = 120

        /**
         * 调用单例对象
         */
        private val instance: NetImageClient
            private get() = RDClientInstance.instance

        /**
         * @return 指定service实例
         */
        fun <T> getService(clazz: Class<T>): T {
            return instance.retrofit.create(clazz)
        }
    }

    /**
     * 私有化构造方法
     */
    init {
        // 创建一个OkHttpClient
        val builder = OkHttpClient.Builder()
        // 设置网络请求超时时间
        builder.readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
        builder.writeTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
        builder.connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
        if (BuildConfig.DEBUG) // 打印参数
        builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        // 失败后尝试重新请求
        builder.retryOnConnectionFailure(true)
        retrofit = Retrofit.Builder()
            .baseUrl(AppParams.net_url)
            .client(builder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }
}